import { ExmlFileStat } from './searchFileModel';
import { IWorkspaceService } from 'egret/platform/workspace/common/workspace';
import { IEgretProjectService } from 'egret/exts/exml-exts/project';
import * as path from 'path';
import { sync } from 'glob';
import URI from '../../../../base/common/uri';


/**
 * 搜索文件的数据
 */
export class SearchFileData {

	private workspacePath: string = '';
	constructor(
		@IEgretProjectService private projectService: IEgretProjectService,
		@IWorkspaceService private workspaceService: IWorkspaceService,
	) {
		if (this.workspaceService.getWorkspace()) {
			this.workspacePath = this.workspaceService.getWorkspace().uri.fsPath;
		}
	}

	/**
	 * 得到根节点
	 */
	public async getRoot(): Promise<ExmlFileStat> {
		await this.projectService.ensureLoaded();
		await this.projectService.exmlConfig.ensurePaserCenterInited();
		const root = new ExmlFileStat();
		const exmlConfig = this.projectService.exmlConfig;
		const skinPaths = exmlConfig.getPaths();

		for (const skinPath in skinPaths) {
			const url = exmlConfig.getExmlUri(skinPath);
			if (url) {
				const exmlFileStat = new ExmlFileStat();
				exmlFileStat.fileName = path.basename(url.fsPath);
				exmlFileStat.resource = url;
				exmlFileStat.parent = root;
				let targetPath = url.fsPath;
				if (targetPath.indexOf(this.workspacePath) == 0) {
					targetPath = targetPath.slice(this.workspacePath.length);
				}
				exmlFileStat.path = targetPath;
				exmlFileStat.className = skinPaths[skinPath] || skinPath;
				root.children.push(exmlFileStat);
			}
		}
		const search_includes = this.projectService.projectModel.EgretProperties.ui_editor?.includes;
		if (search_includes) {
			search_includes.forEach(search_include => {
				root.children.push(...sync(path.join(this.workspacePath, search_include)).map(file => {
					const url = URI.file(file);
					const exmlFileStat = new ExmlFileStat();
					exmlFileStat.fileName = path.basename(url.fsPath);
					exmlFileStat.resource = url;
					exmlFileStat.parent = root;
					let targetPath = url.fsPath;
					if (targetPath.indexOf(this.workspacePath) == 0) {
						targetPath = targetPath.slice(this.workspacePath.length);
					}
					exmlFileStat.path = targetPath;
					exmlFileStat.className = path.basename(url.fsPath, path.extname(url.fsPath));
					return exmlFileStat;
				}))
			})
		}
		return root;
	}
}